import { fileHost } from "@/api/config";
/**
 * 上传
 * @param file
 * @returns Promise<string>
 */

export function upload(
  file: File,
  dir: string,
  isNewName = false
): Promise<string> {
  // eslint-disable-next-line no-async-promise-executor
  return new Promise(async (resolve, reject) => {
    try {
      // 上传
      const name = isNewName ? new Date().getTime() + file.name : file.name;
      const formData = new FormData();
      formData.append("key", `${dir}/${name}`);
      formData.append("file", file);
      formData.append("name", name);
      const res = await fetch(fileHost, {
        method: "POST",
        body: formData
      });
      if (res.status === 204) {
        resolve(`${fileHost}/${dir}/${name}`);
      } else {
        reject("");
      }
    } catch (err) {
      reject(err);
    }
  });
}
/**
 * 下载
 */
export function download(path: string) {
  return new Promise((resolve, reject) => {
    // 下载
    fetch(path, {
      method: "GET"
    }).then(
      res => {
        const blob = res.blob();
        resolve(blob);
      },
      err => {
        reject(err);
      }
    );
  });
}
